package com.truyensex.model;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

public class XmlOperationFromFile extends XmlOperation{
	private InputStream is = null;
	public XmlOperationFromFile() 
	{
	}
	public XmlOperationFromFile(InputStream is)
	{
		this.is = is;
	}
	
	@Override
	public void readXml() {
		ArrayList<Article> listArticle = new ArrayList<Article>();
		 try {
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder builder = factory.newDocumentBuilder();
	            Document doc = builder.parse(is);
				Log.i("instance","Root element :" + doc.getDocumentElement().getNodeName());
				NodeList nList = doc.getElementsByTagName("Truyen");
				for (int temp = 0; temp < nList.getLength(); temp++) {
					Node nNode = nList.item(temp);
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
						Element eElement = (Element) nNode;
						Element elementId = (Element)eElement.getElementsByTagName("Id").item(0);
						Element elementTen = (Element)eElement.getElementsByTagName("Ten").item(0);
						Element elementNoiDung = (Element)eElement.getElementsByTagName("NoiDung").item(0);
						Element elementNgayDang = (Element)eElement.getElementsByTagName("NgayDang").item(0);
						Element elementTacGia = (Element)eElement.getElementsByTagName("TacGia").item(0);
						Element elementTrangThai = (Element)eElement.getElementsByTagName("TrangThai").item(0);
						Integer id = Integer.parseInt(elementId.getTextContent());
						Log.i("id","id :" + id);
						SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
						Log.i("date before",elementNgayDang.getTextContent()  );
						
						String dateInString = elementNgayDang.getTextContent();
						Date date = (Date) sdf.parse(dateInString);
						Boolean status = Boolean.parseBoolean(elementTrangThai.getTextContent());
						Article article = new Article(id, elementTen.getTextContent(),elementNoiDung.getTextContent(), date, elementTacGia.getTextContent(), status);
						listArticle.add(article);
					}
				}
			    } catch (Exception e) {
			    	e.printStackTrace();
			    }
		 this.listObject.clear();
		 this.listObject.addAll(listArticle);
	}
	

}
